<?php
/**
 * 后台桌号管理接口
 */
namespace App\Api\Controllers\Merchant;

use App\Models\MerchantStoreAppidSecret;
use App\Models\MerchantStoreQrcodeRule;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Models\MerchantStoreMoneyQrcode;
use App\Api\Controllers\Merchant\StoreWechatTicketController;
use SimpleSoftwareIO\QrCode\Generator;

class StoreMoneyQrcodeController extends StoreWechatTicketController
{
    protected $wx_qrcode_dir;
    protected $wechat_qrcode_rule;  // 微信小程序二维码规则地址
    protected $wechat_pages_url;    // 微信小程序扫码点餐页面地址

    public function __construct()
    {
        $this->wx_qrcode_dir        = 'appletMoneyQrCode';
        $this->wechat_pages_url     = 'pages/payment/payment';
        $this->wechat_qrcode_rule   = 'https://test.yunsoyi.cn/applet/payment?store_id=';
    }

    /**
     * 获取小程序收款码列表
     * @param Request $request
     * @return array
     */
    public function getMoneyQrcodeLists(Request $request)
    {
        // 接收参数
        $input = $request->all();
        $page = $input['p'] ?? 1;
        $limit = $input['l'] ?? 10;
        $start = abs(($page - 1) * $limit);

        // 获取该商户名下所有门店id
        $store_ids = $this->getMerchantStores();
        $input['store_ids'] = $store_ids;

        // 查询门店列表信息
        $model = new MerchantStoreMoneyQrcode();
        $list = [];
        $count = $model->getMoneyQrcodeCount($input);
        if ($count > 0) {
            $list = $model->getMoneyQrcodePageList($input, $start, $limit);
            foreach ($list as $k => $v) {
                $list[$k]['wechat_applet_qrcode_url_full'] = $this->changeImgUrl($v['wechat_applet_qrcode'], 3);
                $list[$k]['common_qrcode_url_full'] = $this->changeImgUrl($v['common_qrcode'], 3);
            }
        }

        return $this->sys_response_layui(1, '请求成功', $list, $count);
    }

    /**
     * 获取微信小程序收款码
     * @param $input
     * @return string
     * @throws string EasyWeChat 异常
     */
    public function getWechatAppletMoneyQrcode($input)
    {
        $dir = $this->wx_qrcode_dir;
        // 检查存放小程序码文件是否存在
        if (!is_dir(public_path($dir . '/'))) {
            mkdir(public_path($dir . '/'), 0777);
        }
        // 小程序码编号
        $code_number = 'wx_money_qrcode_' . $input['store_id'];

        // 获取微信小程序码
        $config = [
            'app_id' => $input['wechat_appid'],
            'secret' => $input['wechat_secret'],
            // 'app_id' => 'wxc5683deee198a280',
            // 'secret' => '32e36393ed4283cde14e6b636dc9cdf8',
        ];
        $app = Factory::miniProgram($config);

        // 限制个数小程序码scene参数无限制
        $response = $app->app_code->get($this->wechat_pages_url);

        $filename = '';
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(public_path($dir . '/'), $code_number . '.png');
        }

        return '/'  . $dir. '/' . $filename;
    }

    /**
     * 创建小程序收款码
     * @param Request $request
     * @return array
     */
    public function createAppletMoneyQrcode(Request $request)
    {
        // 接收参数
        $input = $request->all();

        try {
            $common_applet_qrcode_dir = 'tableAppletCommonQrCode/';

            // 检查存放小程序收款码文件夹是否存在
            if (!is_dir(public_path($common_applet_qrcode_dir))) {
                mkdir(public_path($common_applet_qrcode_dir), 0777);
            }

            // 参数校验
            $check_data = [
                'store_id' => '门店号',
            ];
            $check = $this->check_required($input, $check_data);
            if ($check) {
                return $this->sys_response(40000, $check);
            }

            // 小程序页面-扫码点餐
            $input['pages_url'] = $this->wechat_pages_url;
            // 生成桌号id
            $table_id = date('YmdHis', time());
            $input['table_id'] = $table_id;
            // 二维码地址
            $input['prefix'] = $this->wechat_qrcode_rule . $input['store_id'];
            // 二维码规则类型
            $input['qrcode_type'] = 2;

            $model = new MerchantStoreMoneyQrcode();
            $merchantStoreModel = new MerchantStoreAppidSecret();
            $merchantStoreQrcodeRuleModel = new MerchantStoreQrcodeRule();

            // 获取门店小程序信息
            $merchantStoreInfo = $merchantStoreModel->getStoreAppIdSecret($input['store_id']);
            $merchantStoreQrcodeRuleInfo = $merchantStoreQrcodeRuleModel->getInfo($input);
            if (!$merchantStoreInfo) {
                return $this->sys_response(40000, '门店对应小程序信息未配置，请完善');
            }
            $input['wechat_appid'] = $merchantStoreInfo->wechat_appid ?? '';
            $input['wechat_secret'] = $merchantStoreInfo->wechat_secret ?? '';
            $input['alipay_appid'] = $merchantStoreInfo->wechat_appid ?? '';
            $input['alipay_secret'] = $merchantStoreInfo->alipay_secret ?? '';
            $wechat_common_qrcode = $merchantStoreQrcodeRuleInfo->wechat_common_qrcode_rule ?? '';
            $alipay_common_qrcode = $merchantStoreQrcodeRuleInfo->wechat_common_qrcode_rule ?? '';

            // 三方配置微信聚合码地址
            $this->createQrcodeRule($input);

            // 获取微信小程序码
            $wechat_applet_qrcode = $this->getWechatAppletMoneyQrcode($input);

            if ($wechat_common_qrcode != $input['prefix']) {
                // 三方配置微信聚合码地址
                $this->createQrcodeRule($input);
                // 插入数据
                $data = [
                    'store_id' => $input['store_id'],
                    'wechat_common_qrcode_rule' => $input['prefix'],
                    'qrcode_type' => 2,
                    'created_at' => date('Y-m-d h:i:s', time()),
                    'updated_at' => date('Y-m-d h:i:s', time()),
                ];
                $merchantStoreQrcodeRuleModel->insertData($data);
            }

            // 如果没有配置微信、支付宝普通二维码地址，且微信、支付宝二维码地址不一致，则不生成聚合二维码
            // if (
            //     !empty($wechat_common_qrcode)
            //     && !empty($alipay_common_qrcode)
            //     && ($wechat_common_qrcode == $alipay_common_qrcode)
            // ) {
            //     $common_qrcode_name = 'applet_money_common_' . $input['store_id'] . '.png';
            //     $common_qrcode_name_full = '/tableAppletCommonQrCode/' . $common_qrcode_name;
            //     $generator = new Generator();
            //     $generator->format('png')->size(300)->generate($input['prefix'], public_path('tableAppletCommonQrCode/' . $common_qrcode_name));
            // } else {
            //     $common_qrcode = '';
            //     $common_qrcode_name_full = '';
            // }

            $common_qrcode_name = 'applet_money_common_' . $input['store_id'] . '.png';
            $common_qrcode_name_full = '/tableAppletCommonQrCode/' . $common_qrcode_name;
            $generator = new Generator();
            $generator->format('png')->size(300)->generate($input['prefix'], public_path('tableAppletCommonQrCode/' . $common_qrcode_name));

            // 插入数据
            $data = [
                'store_id' => $input['store_id'],
                'wechat_appid' => $merchantStoreInfo->wechat_appid ?? '',
                'alipay_appid' => $merchantStoreInfo->alipay_appid ?? '',
                'wechat_applet_qrcode' => $wechat_applet_qrcode,
                'alipay_applet_qrcode' => '',
                'common_qrcode' => $common_qrcode_name_full,
                'created_at' => date('Y-m-d h:i:s', time()),
                'updated_at' => date('Y-m-d h:i:s', time()),
            ];
            $insertRes = $model->insertData($data);
            if (!$insertRes) {
                return $this->sys_response(40000);
            }

            return $this->sys_response_layui(1, '请求成功');
        } catch (\Exception $e) {
            return $this->sys_response(40000, $e->getMessage());
        }
    }

}
